<?php
namespace app\api\controller;
use think\Db;
use think\Controller;
use think\Session;

class Exercises extends Controller
{
    public function getList()
    {   
        $type=input('type');
        if($type==0){
        $result=db('exercises')->where('elevel',0)->select();
        if($result)
        {
            echo json_encode($result);
        }
        else
            echo json_encode(['0']);
        }
        if($type==1){
        $result=db('exercises')->where('elevel',1)->select();
        if($result)
        {
            echo json_encode($result);
        }
        else
            echo json_encode(['0']);
        }
        if($type==2){
        $result=db('exercises')->where('elevel',2)->select();
        if($result)
        {
            echo json_encode($result);
        }
        else
            echo json_encode(['0']);
        }
       
        die();
    }
    public function getDetail(){
         $id=input('id');
        $result=db('exercises')->where('exerid',$id)->find();
        $result2=db('enroll')->where('exerid',$result['exerid'])->find();
        if($result2) $flag=1;
        else $flag=0;
        if($result)
        {
            echo json_encode([$result,'flag'=>$flag]);
        }
        else
            echo json_encode(['0']);
    }
    public function enroll(){
        $id=input('id');
        if(Session::has('uid')){
        $result=db('enroll')->where('exerid',$id)->find();
        if($result){
           echo json_encode(["status"=>0,"message"=>"have enrolled"]);
        }
        else{
           $data=[
        'exerid'=>input('id'),
        'etime'=>date('Y-m-d H:i:s',time()),
        'uid'=>Session::get('uid'),
        ];
         if( Db::name("enroll")->insert($data)){
           echo json_encode(["status"=>1,"message"=>"success"]);
        }
        else{
           echo json_encode(["status"=>0,"message"=>"fail1"]);
         }
        }
    }
        else{
            echo json_encode(["status"=>0,"message"=>"not login"]);
        }
    
    }
    public function cancel(){
        $id=input('id');
        if(Session::has('uid')){
        $result=db('enroll')->where('exerid',$id)->find();
        if($result){
           if(Db::table("enroll")->delete($result['eid'])){
            echo json_encode(["status"=>1,"message"=>"success"]);
           }
        }
        else{
           echo json_encode(["status"=>0,"message"=>"not enroll"]);
        }
       }
        else{
            echo json_encode(["status"=>0,"message"=>"not login"]);
        }
    
    }

}